<template>
  <div class="assessment-container">
    <!-- 整个页面的loading效果 -->
    <div v-if="loading" class="global-loading">
      <div class="loading-content">
        <el-loading :fullscreen="true" text="正在加载评估内容..." spinner="el-icon-loading" background="rgba(0, 0, 0, 0.8)" />
      </div>
    </div>
    <el-card class="header-card" shadow="hover">
      <div class="header">
        <h1>就业成熟度评估</h1>
      </div>
    </el-card>

    <el-card class="chat-card" shadow="hover" ref="chatCardRef">
      <div class="chat-container" ref="chatContainer">
        <!-- 聊天区域的loading只在非全局loading时显示 -->
        <div v-if="isLoading" class="loading-container">
          <el-skeleton :rows="3" animated />
        </div>
        <div v-else class="messages-container">
          <el-timeline>
            <el-timeline-item
              v-for="(message, index) in messages"
              :key="index"
              :timestamp="message.type === 'user' ? '我' : 'AI评估官'"
              :type="message.type === 'user' ? 'success' : 'primary'"
              :icon="message.type === 'user' ? User : ChatRound"
            >
              <el-card :class="`message-card ${message.type}`" shadow="hover">
                <template v-if="message.loading && message.type === 'ai'">
                  <div class="typing-indicator">
                    <span class="typing-dot"></span>
                    <span class="typing-dot"></span>
                    <span class="typing-dot"></span>
                  </div>
                </template>
                <template v-else>
                  {{ message.content }}
                </template>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-card>

    <el-card class="input-card" shadow="hover">
      <el-input
        v-model="userInput"
        type="textarea"
        :rows="3"
        placeholder="请输入您的回答..."
        :disabled="loading || isAssessmentCompleted"
        @keyup.enter.ctrl="sendMessage"
        clearable
      />
      <div class="input-actions">
        <el-tooltip v-if="!isAssessmentCompleted" content="按 Ctrl + Enter 快速发送" placement="top">
          <el-tag size="small">
            <el-icon><Keyboard /></el-icon>
            Ctrl + Enter
          </el-tag>
        </el-tooltip>
        <el-button
          type="primary"
          :icon="isAssessmentCompleted ? Document : Send"
          @click="sendMessage"
          :disabled="!userInput.trim() || loading || isAssessmentCompleted"
          class="send-button"
        >
          {{ isAssessmentCompleted ? '查看报告' : '发送' }}
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';
import { ElButton, ElInput, ElCard, ElProgress, ElSkeleton, ElTimeline, ElTimelineItem, ElTag, ElTooltip } from 'element-plus';
import { Loading, User, ChatRound, Document } from '@element-plus/icons-vue';
import mockService from '../services/mockAssessmentService.js';

const router = useRouter();
const route = useRoute();
const chatContainer = ref(null);

// 状态管理
const messages = ref([]);
const userInput = ref('');
const loading = ref(true); // 全局loading状态
const isLoading = ref(false); // 聊天区域loading状态
const isTyping = ref(false);
const questionCount = ref(0);
const isAssessmentCompleted = ref(false);
const conversationId = ref(route.params.conversationId || '');
const chatCardRef = ref(null);

// 问题计数仍保留但不显示在UI上

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || loading.value || isAssessmentCompleted.value) return;

  const message = userInput.value.trim();
  userInput.value = '';

  // 添加用户消息到界面
  messages.value.push({ type: 'user', content: message });
  
  // 立即滚动到底部
  await nextTick();
  scrollToBottom();
  
  // 设置聊天区域的加载状态
  isLoading.value = true;
  
  // 添加AI回复的占位符，显示loading状态
  const aiMessageIndex = messages.value.push({ type: 'ai', content: '', loading: true }) - 1;
  
  // 再次滚动到底部以显示loading占位符
  await nextTick();
  scrollToBottom();

  try {
    let responseData;
    
    // 尝试调用后端API
    try {
      const response = await axios.post('/api/assessment/init', {
        message,
        conversationId: conversationId.value
      });
      responseData = response.data;
    } catch (apiError) {
      console.log('后端API不可用或返回错误，使用默认问题生成逻辑');
      throw apiError; // 抛出错误以便使用fallback逻辑
    }

    // 处理API返回的响应数据
    if (responseData && responseData.response) {
      const { response: aiResponse, isReport, questionCount: newCount } = responseData;

      // 检查AI响应是否有效且不为用户消息的重复
      if (aiResponse && typeof aiResponse === 'string' && aiResponse.trim() && aiResponse !== message) {
        // 更新AI回复内容，移除loading状态
        messages.value[aiMessageIndex] = { type: 'ai', content: aiResponse, loading: false };

        // 更新计数
        if (newCount !== undefined) {
          questionCount.value = newCount;
        }

        if (isReport) {
          isAssessmentCompleted.value = true;
          // 延迟跳转到报告页面
          setTimeout(() => {
            router.push(`/report/${conversationId.value}`);
          }, 2000);
        }
      } else {
        // 如果响应无效或重复用户消息，使用默认问题逻辑
        throw new Error('无效的AI响应或重复消息');
      }
    } else {
      throw new Error('API返回格式错误');
    }
  } catch (error) {
    console.error('发送消息失败，使用默认问题生成逻辑:', error);
    
    // 根据当前问题计数生成相应的维度问题
    let fallbackQuestion = "请继续描述您的相关经验和想法。";
    
    // 简单的维度问题逻辑 - 根据questionCount生成对应维度的问题
    if (questionCount.value >= 1) {
      const dimensions = [
        { name: "职业认知", questions: [
          "您了解互联网行业前端开发的市场规模和发展趋势吗？",
          "互联网行业前端开发的日常工作内容和核心职责有哪些？",
          "互联网行业前端开发的晋升路径和薪资发展情况如何？"
        ]},
        { name: "专业技能", questions: [
          "前端开发通常需要掌握哪些核心技能？您目前掌握了其中的哪些？",
          "您是否有与前端开发相关的实践经验或项目经历？请详细描述。",
          "前端开发常用的工具有哪些？您是否熟悉这些工具的使用？"
        ]},
        { name: "通用能力", questions: [
          "在互联网行业中，沟通协作非常重要，请描述一次您团队合作完成任务的经历。",
          "前端开发工作中可能会遇到哪些压力和挑战？您通常如何应对？",
          "请分享一次您在团队中有效沟通解决问题的经历。"
        ]},
        { name: "求职技能", questions: [
          "您的简历中是否突出了与前端开发相关的技能和经验？请举例说明。",
          "针对互联网行业前端开发的面试，您做了哪些具体准备？",
          "您了解互联网行业的主要招聘渠道和招聘季节吗？"
        ]},
        { name: "心理素质", questions: [
          "互联网行业的工作压力通常较大，您对职场生活有什么具体期望和担忧？",
          "您如何看待从学生到前端开发职场人的角色转变？",
          "如果求职过程中遇到挫折，您会如何调整自己的心态？"
        ]},
        { name: "环境适应", questions: [
          "您对互联网行业的职场文化和工作氛围有什么了解？",
          "您认为职场和校园最大的区别是什么？您准备如何应对？",
          "在前端开发工作中，您会如何处理与上级和同事的关系？"
        ]}
      ];
      
      // 计算当前应该属于哪个维度的问题（从第一个维度开始，每个维度3个问题）
      const dimIndex = Math.floor((questionCount.value - 1) / 3);
      const qIndex = (questionCount.value - 1) % 3;
      
      if (dimIndex < dimensions.length) {
        const dimension = dimensions[dimIndex];
        if (qIndex < dimension.questions.length) {
          fallbackQuestion = `【${dimension.name}】${dimension.questions[qIndex]}`;
        }
      }
    }
    
    // 更新AI回复内容，移除loading状态
    messages.value[aiMessageIndex] = { 
      type: 'ai', 
      content: fallbackQuestion,
      loading: false 
    };
    
    // 增加问题计数
    questionCount.value += 1;
  } finally {
    isLoading.value = false; // 使用isLoading控制聊天区域的加载状态
    // 滚动到底部
    await nextTick();
    scrollToBottom();
  }
};

// 滚动到底部
const scrollToBottom = () => {
  // 使用requestAnimationFrame确保在DOM更新后执行滚动
  requestAnimationFrame(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    }
    // 同时确保chat-card也滚动到底部
    if (chatCardRef.value) {
      const cardElement = chatCardRef.value.$el || chatCardRef.value;
      if (cardElement) {
        cardElement.scrollTop = cardElement.scrollHeight;
      }
    }
  });
};

// 生成对话ID
const generateConversationId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

// 初始化评估
const initializeAssessment = async () => {
  // 如果没有对话ID，生成一个
  if (!conversationId.value) {
    conversationId.value = generateConversationId();
    // 重定向到带有对话ID的URL
    router.push(`/assessment/${conversationId.value}`);
    return;
  }

  loading.value = true;
  try {
    // 设置默认的第一个问题（硬编码，3秒后使用）
    const defaultFirstQuestion = "您好，请问您想了解哪个行业的哪个职业呢？例如：\"互联网行业 - 数据分析师\"、\"制造业 - 机械工程师\"、\"金融行业 - 客户经理\"等。";
    
    // 设置超时标志和定时器
    let timeoutReached = false;
    const timeoutId = setTimeout(() => {
      timeoutReached = true;
      if (loading.value) {
        console.log('请求超时，使用默认问题');
        messages.value.push({ type: 'ai', content: defaultFirstQuestion });
        questionCount.value = 1;
        loading.value = false;
        nextTick(() => scrollToBottom());
      }
    }, 3000); // 3秒超时

    let responseData;
    
    try {
      // 尝试调用后端API获取第一个问题
      const response = await axios.post('/api/assessment/init', {
        message: '开始就业成熟度评估',
        conversationId: conversationId.value
      });
      responseData = response.data;
    } catch (apiError) {
      console.log('后端API调用失败或超时');
      // 不使用mockService，直接使用默认问题
      // 清除超时定时器
      clearTimeout(timeoutId);
      
      // 如果超时还没触发，使用默认问题
      if (!timeoutReached) {
        console.log('使用默认问题作为第一个问题');
        messages.value.push({ type: 'ai', content: defaultFirstQuestion });
        questionCount.value = 1;
      }
      return;
    }

    // 清除超时定时器
    clearTimeout(timeoutId);
    
    // 如果超时还没触发，使用返回的数据
    if (!timeoutReached) {
      const { response: firstQuestion, questionCount: newCount } = responseData || {};
      // 确保firstQuestion是有效的字符串，避免空响应
      if (firstQuestion && typeof firstQuestion === 'string' && firstQuestion.trim()) {
        messages.value.push({ type: 'ai', content: firstQuestion });
      } else {
        // 如果后端返回无效数据，使用默认问题
        console.log('后端返回无效数据，使用默认问题');
        messages.value.push({ type: 'ai', content: defaultFirstQuestion });
      }
      
      if (newCount !== undefined) {
        questionCount.value = newCount;
      }
    }
  } catch (error) {
    console.error('初始化评估失败:', error);
    // 出错时使用默认问题
    const defaultFirstQuestion = "您好，请问您想了解哪个行业的哪个职业呢？例如：\"互联网行业 - 数据分析师\"、\"制造业 - 机械工程师\"、\"金融行业 - 客户经理\"等。";
    messages.value.push({
      type: 'ai',
      content: defaultFirstQuestion
    });
    questionCount.value = 1;
  } finally {
    loading.value = false;
    // 滚动到底部
    await nextTick();
    scrollToBottom();
  }
};

// 生命周期钩子
onMounted(() => {
  initializeAssessment();
  
  // 监听messages数组变化，确保滚动条始终在底部
  watch(() => messages.value.length, () => {
    nextTick(() => {
      scrollToBottom();
    });
  });
  
  // 监听loading状态变化，确保加载完成后滚动到底部
  watch(loading, () => {
    nextTick(() => {
      scrollToBottom();
    });
  });
});
</script>

<style scoped>
.assessment-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  height: 100vh;
  gap: 1rem;
}

.header-card {
  margin-bottom: 0;
}

.header {
  text-align: center;
}

.header h1 {
  color: #333;
  margin-bottom: 1rem;
  font-size: 1.8rem;
}

.progress-info {
  margin-top: 0.5rem;
}

.progress-text {
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 0.5rem;
  text-align: center;
}

.chat-card {
  flex: 0.8;
  display: flex;
  flex-direction: column;
  margin-bottom: 0;
  overflow-y: auto;
}

.chat-container {
  overflow-y: auto;
  flex: 1;
}

.loading-container {
  padding: 2rem;
}

.global-loading {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.messages-container {
  padding: 0 0.5rem;
}

.message-card {
  margin-top: 0.5rem;
  border-radius: 8px;
}

.message-card.user {
  border-left: 4px solid #67c23a;
}

.message-card.ai {
  border-left: 4px solid #409eff;
}

.input-card {
  margin-bottom: 0;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 0.8rem;
}

.send-button {
  min-width: 120px;
}

.typing-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 0;
}

.typing-dot {
  width: 8px;
  height: 8px;
  margin: 0 2px;
  background-color: #409eff;
  border-radius: 50%;
  display: inline-block;
  animation: typing 1.4s infinite ease-in-out both;
}

.typing-dot:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

@media (max-width: 768px) {
  .assessment-container {
    padding: 0.5rem;
    height: 100vh;
  }
  
  .header h1 {
    font-size: 1.5rem;
  }
  
  .input-actions {
    flex-direction: column;
    gap: 0.5rem;
    align-items: stretch;
  }
  
  .send-button {
    min-width: auto;
  }
}
</style>